package com.example.farmrental.service;

import com.example.farmrental.dto.SetmealDto;
import com.example.farmrental.dto.PageResponse;
import com.example.farmrental.entity.Machinery;
import com.example.farmrental.entity.Setmeal;
import com.example.farmrental.repository.MachineryRepository;
import com.example.farmrental.repository.SetmealRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 套餐服务层
 */
@Service
public class SetmealService {

    @Autowired
    private SetmealRepository setmealRepository;

    @Autowired
    private MachineryRepository machineryRepository;

    /**
     * 获取所有套餐列表
     */
    public List<Setmeal> getAllSetmeals() {
        return setmealRepository.findAll();
    }

    /**
     * 分页查询套餐列表，支持按分类筛选和关键词搜索
     */
    public PageResponse<Setmeal> getSetmealsPage(int page, int size, String category, String keyword) {
        // 创建分页对象，按更新时间倒序排列
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "updateTime"));
        
        Page<Setmeal> setmealPage;
        boolean hasCategory = StringUtils.hasText(category) && !"全部".equals(category);
        boolean hasKeyword = StringUtils.hasText(keyword);
        
        if (hasCategory && hasKeyword) {
            // 同时有分类和关键词筛选
            setmealPage = setmealRepository.findByCategoryAndNameContainingIgnoreCase(category, keyword, pageable);
        } else if (hasCategory) {
            // 只有分类筛选
            setmealPage = setmealRepository.findByCategory(category, pageable);
        } else if (hasKeyword) {
            // 只有关键词搜索
            setmealPage = setmealRepository.findByNameContainingIgnoreCase(keyword, pageable);
        } else {
            // 查询所有
            setmealPage = setmealRepository.findAll(pageable);
        }
        
        // 主动加载农机数据，解决懒加载问题
        setmealPage.getContent().forEach(setmeal -> {
            // 触发农机数据的加载
            setmeal.getMachinery().size();
        });
        
        return new PageResponse<>(
            setmealPage.getContent(),
            setmealPage.getTotalElements(),
            setmealPage.getNumber(),
            setmealPage.getSize()
        );
    }

    /**
     * 根据ID获取套餐
     */
    public Optional<Setmeal> getSetmealById(Long id) {
        return setmealRepository.findById(id);
    }

    /**
     * 新增套餐
     */
    @Transactional
    public Setmeal createSetmeal(SetmealDto setmealDto) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto, setmeal);

        // 处理关联的农机
        if (setmealDto.getMachineryIds() != null && !setmealDto.getMachineryIds().isEmpty()) {
            List<Machinery> machineryList = machineryRepository.findAllById(setmealDto.getMachineryIds());
            setmeal.setMachinery(new HashSet<>(machineryList));
        }

        return setmealRepository.save(setmeal);
    }

    /**
     * 更新套餐
     */
    @Transactional
    public Optional<Setmeal> updateSetmeal(Long id, SetmealDto setmealDto) {
        return setmealRepository.findById(id).map(existingSetmeal -> {
            BeanUtils.copyProperties(setmealDto, existingSetmeal, "id");

            // 清空并重新设置关联的农机
            existingSetmeal.getMachinery().clear();
            if (setmealDto.getMachineryIds() != null && !setmealDto.getMachineryIds().isEmpty()) {
                List<Machinery> machineryList = machineryRepository.findAllById(setmealDto.getMachineryIds());
                existingSetmeal.setMachinery(new HashSet<>(machineryList));
            }

            return setmealRepository.save(existingSetmeal);
        });
    }

    /**
     * 删除套餐
     */
    public void deleteSetmeal(Long id) {
        setmealRepository.deleteById(id);
    }

    /**
     * 批量删除套餐
     */
    @Transactional
    public void batchDeleteSetmeals(List<Long> ids) {
        ids.forEach(this::deleteSetmeal);
    }

    /**
     * 更新套餐状态
     */
    @Transactional
    public Optional<Setmeal> updateSetmealStatus(Long id, String status) {
        return setmealRepository.findById(id).map(setmeal -> {
            setmeal.setStatus(status);
            return setmealRepository.save(setmeal);
        });
    }
}